﻿using System;
using System.Collections;
using System.Text;
using System.Text.RegularExpressions;
using System.Data;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ByteSite.Common;
using System.Linq.Expressions;
using System.Linq;
using SqlSugar;

namespace ByteSite.Web.admin.form
{
    public partial class data_list : Web.UI.ManagePage
    {
        protected int form_id;
        protected int totalCount;
        protected int page;
        protected int pageSize;

        protected string form_name = string.Empty;
        protected string keywords = string.Empty;
        protected DataTable table;
        protected List<Entitys.dt_form_attribute_field> fieldList;
        protected void Page_Load(object sender, EventArgs e)
        {
            this.form_id = DTRequest.GetQueryInt("form_id");
            this.keywords = DTRequest.GetQueryString("keywords");

            if (form_id == 0)
            {
                JscriptMsg("数据表格不正确！", "back");
                return;
            }
            this.form_name = new BLL.forms().GetFormName(this.form_id); //取得频道名称
            this.pageSize = GetPageSize(10); //每页数量
            if (!Page.IsPostBack)
            {
                ChkAdminLevel("form_data_" + this.form_name, DTEnums.ActionEnum.View.ToString()); //检查权限
                RptBind(this.form_id, CombSqlTxt(this.keywords), "sort_id asc,add_time desc,id desc");
            }
        }

        

        #region 数据绑定=================================
        private void RptBind(int _form_id, Expression<Func<Entitys.form, bool>> whereExpression, string _orderby)
        {
            this.page = DTRequest.GetQueryInt("page", 1);

            this.txtKeywords.Text = this.keywords;
            //图表或列表显示
            BLL.form bll = new BLL.form();
            Entitys.dt_forms formsModel = new BLL.forms().GetModel(this.form_id);

            table = new DataTable();
            DataColumn columns = null;

            columns = table.Columns.Add("id", Type.GetType("System.Int32"));
            columns = table.Columns.Add("data_name", Type.GetType("System.String"));
            fieldList = new List<Entitys.dt_form_attribute_field>();
            if (formsModel.show_form_fields != null)
            {
                if (formsModel.show_form_fields.Count > 0)
                {
                    BLL.form_attribute_field fieldBll = new BLL.form_attribute_field();
                    foreach (Entitys.dt_form_show_column column in formsModel.show_form_fields)
                    {
                        Entitys.dt_form_attribute_field fieldModel = fieldBll.GetModel(Utils.ObjToInt(column.field_id));
                        fieldList.Add(fieldModel);
                        if (fieldModel.data_type.StartsWith("nvarchar") || fieldModel.data_type.StartsWith("varchar") || fieldModel.data_type.StartsWith("ntext") || fieldModel.data_type.StartsWith("text"))
                        {
                            columns = table.Columns.Add(fieldModel.name, Type.GetType("System.String"));
                        }
                        else if (fieldModel.data_type.StartsWith("int"))
                        {
                            if (!string.IsNullOrEmpty(fieldModel.item_option) || fieldModel.item_datasource != 0)
                            {
                                columns = table.Columns.Add(fieldModel.name, Type.GetType("System.String"));
                            }
                            else
                            {
                                columns = table.Columns.Add(fieldModel.name, Type.GetType("System.Int32"));
                            }
                        }
                        else if (fieldModel.data_type.StartsWith("datetime"))
                        {
                            columns = table.Columns.Add(fieldModel.name, Type.GetType("System.DateTime"));
                        }
                        else if (fieldModel.data_type.StartsWith("tinyint"))
                        {
                            columns = table.Columns.Add(fieldModel.name, Type.GetType("System.Byte"));
                        }
                        else if (fieldModel.data_type.StartsWith("decimal"))
                        {
                            columns = table.Columns.Add(fieldModel.name, Type.GetType("System.Decimal"));
                        }
                        else
                        {
                            columns = table.Columns.Add(fieldModel.name, Type.GetType("System.String"));
                        }
                    }
                }
            }
            columns = table.Columns.Add("add_time", Type.GetType("System.DateTime"));
            columns = table.Columns.Add("sort_id", Type.GetType("System.Int32"));
            
            fieldList.OrderBy(x => x.sort_id).OrderBy(x => x.id);

            //获取权限
            List<Entitys.dt_form_data_role> roles = new BLL.form_data_role().GetList(x => x.form_id == _form_id && x.user_id == GetAdminInfo().id, x => x.id);
            string sql = string.Empty;
            List<IConditionalModel> conModels = new List<IConditionalModel>();

            if (roles != null)
            {
                if (roles.Count > 0)
                {
                    foreach (Entitys.dt_form_data_role role in roles)
                    {
                        if (!string.IsNullOrEmpty(role.sql))
                        {
                            sql += role.sql;
                        }
                        else
                        {
                            foreach (Entitys.dt_form_data_role_value v in role.role_value_list)
                            {
                                ConditionalModel model = new ConditionalModel();
                                model.FieldName = v.column;
                                switch (v.type)
                                {
                                    case "Equal":
                                        {
                                            model.ConditionalType = ConditionalType.Equal;
                                        };
                                        break;

                                    case "Like":
                                        {
                                            model.ConditionalType = ConditionalType.Like;
                                        };
                                        break;
                                    case "NoLike":
                                        {
                                            model.ConditionalType = ConditionalType.NoLike;
                                        };
                                        break;
                                    case "GreaterThan":
                                        {
                                            model.ConditionalType = ConditionalType.GreaterThan;
                                        };
                                        break;
                                    case "GreaterThanOrEqual":
                                        {
                                            model.ConditionalType = ConditionalType.GreaterThanOrEqual;
                                        };
                                        break;
                                    case "LessThan":
                                        {
                                            model.ConditionalType = ConditionalType.LessThan;
                                        };
                                        break;
                                    case "LessThanOrEqual":
                                        {
                                            model.ConditionalType = ConditionalType.LessThanOrEqual;
                                        };
                                        break;
                                    case "In":
                                        {
                                            model.ConditionalType = ConditionalType.In;
                                        };
                                        break;
                                    case "NotIn":
                                        {
                                            model.ConditionalType = ConditionalType.NotIn;
                                        };
                                        break;
                                    case "LikeLeft":
                                        {
                                            model.ConditionalType = ConditionalType.LikeLeft;
                                        };
                                        break;
                                    case "LikeRight":
                                        {
                                            model.ConditionalType = ConditionalType.LikeRight;
                                        };
                                        break;
                                    case "NoEqual":
                                        {
                                            model.ConditionalType = ConditionalType.NoEqual;
                                        };
                                        break;
                                    case "IsNullOrEmpty":
                                        {
                                            model.ConditionalType = ConditionalType.IsNullOrEmpty;
                                        };
                                        break;
                                    case "IsNot":
                                        {
                                            model.ConditionalType = ConditionalType.IsNot;
                                        };
                                        break;
                                    case "EqualNull":
                                        {
                                            model.ConditionalType = ConditionalType.EqualNull;
                                        };
                                        break;
                                }
                                model.FieldValue = v.value;
                                conModels.Add(model);
                            }
                        }
                    }
                }
            }

            List<Entitys.form> data = bll.GetList(_form_id, this.pageSize, this.page, whereExpression, conModels, sql, _orderby, out this.totalCount);
            if (data != null)
            {
                if (data.Count > 0)
                {
                    if (fieldList.Count > 0)
                    {
                        foreach (Entitys.form row in data)
                        {
                            DataRow newRow = table.NewRow();
                            newRow["id"] = row.id;
                            newRow["data_name"] = row.data_name;
                            newRow["add_time"] = row.add_time;
                            newRow["sort_id"] = row.sort_id;

                            foreach (Entitys.dt_form_attribute_field c in fieldList)
                            {
                                if (c.item_datasource == 0 && string.IsNullOrEmpty(c.item_option))
                                {
                                    if (c.data_type.StartsWith("nvarchar") || c.data_type.StartsWith("varchar") || c.data_type.StartsWith("ntext") || c.data_type.StartsWith("text"))
                                    {
                                        newRow[c.name] = row.fields[c.name];
                                    }
                                    else if (c.data_type.StartsWith("int"))
                                    {
                                        newRow[c.name] = Utils.ObjToInt(row.fields[c.name]);
                                    }
                                    else if (c.data_type.StartsWith("datetime"))
                                    {
                                        newRow[c.name] = Utils.ObjectToDateTime(row.fields[c.name]).ToString("yyyy/MM/dd HH:mm:ss");
                                    }
                                    else if (c.data_type.StartsWith("tinyint"))
                                    {
                                        newRow[c.name] = Utils.ObjToInt(row.fields[c.name]);
                                    }
                                    else if (c.data_type.StartsWith("decimal"))
                                    {
                                        newRow[c.name] = Utils.ObjToDecimal(row.fields[c.name]).ToString("f2");
                                    }
                                    else
                                    {
                                        newRow[c.name] = row.fields[c.name];
                                    }
                                }
                                else if (c.item_datasource == 0 && !string.IsNullOrEmpty(c.item_option))
                                {
                                    string value = string.Empty;
                                    Dictionary<string, object> dic = new Dictionary<string, object>();
                                    string[] valArr = c.item_option.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
                                    for (int i = 0; i < valArr.Length; i++)
                                    {
                                        string[] valItemArr = valArr[i].Split('|');
                                        if (valItemArr.Length == 2)
                                        {
                                            dic.Add(valItemArr[1], valItemArr[0]);
                                        }
                                    }
                                    string key = row.fields[c.name].ToString();
                                    string[] ks = key.Split(',');
                                    foreach (string k in ks)
                                    {
                                        value += dic[k].ToString() + ",";
                                    }
                                    newRow[c.name] = value.TrimEnd(',');
                                }
                                else if (c.item_datasource != 0)
                                {
                                    string value = string.Empty;
                                    Entitys.dt_custom_list customListModel = new BLL.custom_list().GetModel(Utils.ObjToInt(c.item_datasource));
                                    if (customListModel != null)
                                    {
                                        List<Entitys.list_item> list = new BLL.list_item().GetList(customListModel.table, customListModel.key, customListModel.value, null);
                                        string key = row.fields[c.name].ToString();
                                        string[] ks = key.Split(',');
                                        foreach (string k in ks)
                                        {
                                            value += list.Find(x => x.value == k).key + ",";
                                        }
                                        newRow[c.name] = value.TrimEnd(',');
                                    }
                                }
                            }
                            table.Rows.Add(newRow);
                        }
                    }
                    else
                    {
                        foreach (Entitys.form row in data)
                        {
                            DataRow newRow = table.NewRow();
                            newRow["id"] = row.id;
                            newRow["data_name"] = row.data_name;
                            newRow["add_time"] = row.add_time;
                            newRow["sort_id"] = row.sort_id;
                            table.Rows.Add(newRow);
                        }
                    }
                }
            }


            //this.rptList.DataSource = bll.GetList(_form_id, this.pageSize, this.page, whereExpression, _orderby, out this.totalCount);
            //this.rptList.DataBind();

            //绑定页码
            txtPageNum.Text = this.pageSize.ToString();
            string pageUrl = Utils.CombUrlTxt("data_list.aspx", "form_id={0}&keywords={1}&page={2}",
                _form_id.ToString(), this.keywords, "__id__");
            PageContent.InnerHtml = Utils.OutPageList(this.pageSize, this.page, this.totalCount, pageUrl, 8);
        }
        #endregion

        #region 组合SQL查询语句==========================
        protected Expression<Func<Entitys.form, bool>> CombSqlTxt(string _keywords)
        {
            Expression<Func<Entitys.form, bool>> expression = t => true;
            _keywords = _keywords.Replace("'", "");
            if (!string.IsNullOrEmpty(_keywords))
            {
                expression = expression.And(x => x.data_name.Contains(_keywords));
            }
            return expression;
        }
        #endregion

        #region 返回图文每页数量=========================
        private int GetPageSize(int _default_size)
        {
            int _pagesize;
            if (int.TryParse(Utils.GetCookie("form_data_" + this.form_name + "_page_size", "ByteSitePage"), out _pagesize))
            {
                if (_pagesize > 0)
                {
                    return _pagesize;
                }
            }
            return _default_size;
        }
        #endregion

        //关健字查询
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            Response.Redirect(Utils.CombUrlTxt("data_list.aspx", "form_id={0}&keywords={1}",
                this.form_id.ToString(),txtKeywords.Text));
        }

        //设置分页数量
        protected void txtPageNum_TextChanged(object sender, EventArgs e)
        {
            int _pagesize;
            if (int.TryParse(txtPageNum.Text.Trim(), out _pagesize))
            {
                if (_pagesize > 0)
                {
                    Utils.WriteCookie("form_data_" + this.form_name + "_page_size", "ByteSitePage", _pagesize.ToString(), 43200);
                }
            }
            Response.Redirect(Utils.CombUrlTxt("data_list.aspx", "form_id={0}&keywords={1}",
                this.form_id.ToString(), this.keywords));
        }

        //保存排序
        protected void btnSave_Click(object sender, EventArgs e)
        {
            //ChkAdminLevel("form_data_" + this.form_name, DTEnums.ActionEnum.Edit.ToString()); //检查权限
            //BLL.form bll = new BLL.form();
            //Repeater rptList = this.rptList;

            //for (int i = 0; i < rptList.Items.Count; i++)
            //{
            //    int id = Convert.ToInt32(((HiddenField)rptList.Items[i].FindControl("hidId")).Value);
            //    int sortId;
            //    if (!int.TryParse(((TextBox)rptList.Items[i].FindControl("txtSortId")).Text.Trim(), out sortId))
            //    {
            //        sortId = 99;
            //    }
            //    bll.UpdateField(this.form_id, x => new Entitys.form() { sort_id = sortId }, x => x.id == id);
            //}
            //JscriptMsg("保存排序成功！", Utils.CombUrlTxt("data_list.aspx", "form_id={0}&keywords={1}",
            //    this.form_id.ToString(), this.keywords));
        }

        //批量删除
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            //ChkAdminLevel("form_data_" + this.form_name, DTEnums.ActionEnum.Delete.ToString()); //检查权限
            //int sucCount = 0; //成功数量
            //int errorCount = 0; //失败数量
            //BLL.form bll = new BLL.form();
            //Repeater rptList = this.rptList;
            //for (int i = 0; i < rptList.Items.Count; i++)
            //{
            //    int id = Convert.ToInt32(((HiddenField)rptList.Items[i].FindControl("hidId")).Value);
            //    CheckBox cb = (CheckBox)rptList.Items[i].FindControl("chkId");
            //    if (cb.Checked)
            //    {
            //        if (bll.Delete(this.form_id, id))
            //        {
            //            sucCount++;
            //        }
            //        else
            //        {
            //            errorCount++;
            //        }
            //    }
            //}
            //AddAdminLog(DTEnums.ActionEnum.Edit.ToString(), "删除" + "form_data_" + this.form_name + "数据成功" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            //JscriptMsg("删除成功" + sucCount + "条，失败" + errorCount + "条！", Utils.CombUrlTxt("data_list.aspx", "form_id={0}&keywords={1}",
            //    this.form_id.ToString(), this.keywords));
        }

    }
}